package com.qiaofang.applet.common.filter;

import com.qiaofang.applet.common.context.QfContext;
import com.qiaofang.applet.common.context.QfContextProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 上下文件filter
 * @author QF2019
 */
@Component
public class QfContextInitFilter extends GenericFilterBean {

    @Autowired
    private QfContextProvider contextProvider;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String corporationCode = request.getHeader("corporationCode");
            String cityCode = request.getHeader("cityCode");
            if(StringUtils.isNotBlank(corporationCode) && StringUtils.isNotBlank(cityCode)) {
                contextProvider.setContext(new QfContext(
                        // 集团code
                        corporationCode,
                        // 公司uuid
                        request.getHeader("companyUuid"),
                        // 城市code
                        cityCode,
                        "",
                        ""));
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            contextProvider.removeContext();
        }

    }
}
